package com.ruoyi.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自动生成流水单号
 *
 * @author 张杰
 * @version 2018-12-15
 */
@SuppressWarnings("ALL")
public class SerialNumber {
    // 记录参数
    private String prefix;
    private String recordTime;
    // 自增配件
    private String formatText;
    private SimpleDateFormat dateFormat;
    private final AtomicInteger atomic = new AtomicInteger();

    public SerialNumber() {
        this("");
    }

    public SerialNumber(String prefix) {
        this(prefix, "yyyyMMddHHmmss", 2);
    }

    // 初始化参数
    public SerialNumber(String prefix, String textFormat, int minLenght) {
        this.prefix = prefix;
        this.formatText = "%0" + minLenght + "d";
        this.dateFormat = new SimpleDateFormat(textFormat);
    }

    // 获取自增订单号
    public String getAtomicNumber() {
        // 基础参数准备
        String currentTime = this.dateFormat.format(new Date());
        // 重置计数
        if (!currentTime.equals(this.recordTime)) this.atomic.set(0);
        int increment = this.atomic.incrementAndGet();
        // 格式数据
        String format = String.format(this.formatText, increment);
        // 重置时间
        this.recordTime = currentTime;
        return this.prefix + currentTime + format;
    }
}
